package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamService specParamService;


    //根据商品分类id，查询规格组的集合
    @Override
    public List<SpecGroupDTO> querySpecGroupListByCategoryId(Long cid) {

        return SpecGroupDTO.convertEntityList(list(new QueryWrapper<SpecGroup>().eq("category_id", cid)));
    }



    //根据分类id查询规格组,规格参数
    @Override
    public List<SpecGroupDTO> querySpecGroupListById(Long cid) {
        //根据分类cid查询规格组
        List<SpecGroupDTO> specGroupList = SpecGroupDTO.convertEntityList(this.query().eq("category_id", cid).list());
        //根据分类cid查询规格项
        List<SpecParamDTO> specParamDTOList = SpecParamDTO.convertEntityList(specParamService.query().eq("category_id", cid).list());
        //规格项分组，根据相同的规格组group_id，分组
        Map<Long, List<SpecParamDTO>> listMap = specParamDTOList
                .stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        //将规格项set到规格组中
        specGroupList.
                forEach(specGroupDTO -> specGroupDTO.setParams(listMap.get(specGroupDTO.getId())));

        return specGroupList;
    }



    //新增规格组
    @Override
    @Transactional
    public void addSpecGroup(SpecGroupDTO groupDTO) {
        if (groupDTO != null) {
            this.save(groupDTO.toEntity(SpecGroup.class));
        }
    }


    //修改分组
    @Override
    @Transactional
    public void updateSpecGroup(SpecGroupDTO groupDTO) {
        if (groupDTO != null) {
            this.updateById(groupDTO.toEntity(SpecGroup.class));
        }
    }




}
